/*
 * Copyright (C) 2010-2101 Alibaba Group Holding Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.otter.manager.biz.user.impl;

import com.alibaba.otter.manager.biz.common.exceptions.ManagerException;
import com.alibaba.otter.manager.biz.common.exceptions.RepeatConfigureException;
import com.alibaba.otter.manager.biz.user.UserService;
import com.alibaba.otter.manager.biz.user.dal.ibatis.UserDao;
import com.alibaba.otter.manager.biz.user.dal.dataobject.UserDO;
import com.alibaba.otter.manager.biz.user.dto.UserQueryDTO;
import com.alibaba.otter.shared.common.model.user.User;
import com.alibaba.otter.shared.common.utils.Assert;
import com.mybatisflex.core.paginate.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * TODO Comment of UserServiceImpl
 *
 * @author simon
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    public Page<User> userPage(UserQueryDTO userQueryDTO, Pageable pageable){
        Page<UserDO> userDOPage = userDao.userPage(userQueryDTO, pageable);
        return userDOPage.map(this::doToModel);
    }


    public void createUser(User user) {
        Assert.assertNotNull(user);
        try {
            UserDO userDo = modelToDo(user);
            userDao.uniqueInsert(userDo);
            if (userDo.getId() == 0) {
                String exceptionCause = "exist the same name user in the database.";
                logger.warn("WARN ## " + exceptionCause);
                throw new RepeatConfigureException(exceptionCause);
            }
        } catch (RepeatConfigureException rce) {
            throw rce;
        } catch (Exception e) {
            logger.error("ERROR ## create user has an exception!");
            throw new ManagerException(e);
        }
    }

    public void deleteUser(Long userId) {
        Assert.assertNotNull(userId);
        userDao.deleteById(userId);
    }

    public void updateUser(User user) {
        Assert.assertNotNull(user);
        try {
            UserDO UserDo = modelToDo(user);
            if (userDao.checkUnique(UserDo)) {
                userDao.insertOrUpdate(UserDo,true);
            } else {
                String exceptionCause = "exist the same name user in the database.";
                logger.warn("WARN ## " + exceptionCause);
                throw new RepeatConfigureException(exceptionCause);
            }
        } catch (RepeatConfigureException rce) {
            throw rce;
        } catch (Exception e) {
            logger.error("ERROR ## create user has an exception!");
            throw new ManagerException(e);
        }
    }

    public User findUserById(Long userId) {
        Assert.assertNotNull(userId);
        return doToModel(userDao.selectOneById(userId));
    }

    public List<User> ListAllUsers() {
        List<UserDO> userDos = userDao.selectAll();
        List<User> users = new ArrayList<User>();
        for (UserDO userDo : userDos) {
            users.add(doToModel(userDo));
        }
        return users;
    }

    public List<User> listByCondition(Map<String, Object> condition) {
        List<UserDO> userDos = userDao.listByCondition(condition);
        List<User> users = new ArrayList<>();
        for (UserDO userDo : userDos) {
            users.add(doToModel(userDo));
        }
        return users;
    }

    /**
     * 拿到user总数进行分页
     */
    public int getCount() {
        return userDao.getCount(null);
    }

    public int getCount(Map<String,Object> condition) {
        return userDao.getCount(condition);
    }

    @Override
    public User login(String name, String password) {
        UserDO userDo = userDao.getAuthenticatedUser(name, password);
        if (null == userDo) {
            return null;
        }
        return doToModel(userDo);
    }

    private User doToModel(UserDO userDo) {
        User user = new User();
        user.setId(userDo.getId());
        user.setName(userDo.getRealName());
        user.setDepartment(userDo.getDepartment());
        user.setRealName(userDo.getRealName());
        user.setAuthorizeType(userDo.getAuthorizeType());
        user.setGmtCreate(Date.from(userDo.getGmtCreate()));
        user.setGmtModified(Date.from(userDo.getGmtModified()));
        return user;
    }


    private UserDO modelToDo(User user) {
        UserDO userDo = new UserDO();
        userDo.setId(user.getId());
        userDo.setUsername(user.getName());
        userDo.setPassword(user.getPassword());
        userDo.setDepartment(user.getDepartment());
        userDo.setRealName(user.getRealName());
        userDo.setAuthorizeType(user.getAuthorizeType());
        return userDo;
    }

}
